package com.example.activemq.com.example.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @ Author     ：scw
 * @ Date       ：Created in 上午 11:30 2019/7/29 0014
 * @ Description：通过监听的方式消费
 * @ Modified By：
 * @Version: $version$
 */
public class MessageConsumer1 {//定义ActivMQ的连接地址
    private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
    //定义发送消息的队列名称
    private static final String QUEUE_NAME = "MyMessage";

    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("2*******监听消费者的方式");
        //创建连接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        //打开连接
        connection.start();
        //创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建队列目标
        Destination destination = session.createQueue(QUEUE_NAME);
        //创建消费者
        javax.jms.MessageConsumer consumer1 = session.createConsumer(destination);
        //通过监听的方式消费
        consumer1.setMessageListener(new MessageListener() {
                                         @Override
                                         public void onMessage(Message message) {
                                            if (null!= message && message instanceof TextMessage){
                                                TextMessage textMessage= (TextMessage) message;
                                                try {
                                                    System.out.println("*******监听的消费者接收到消息"+textMessage.getText());
                                                } catch (JMSException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                         }
                                     }


        );
        //保证控制台一直在运行着
        System.in.read();//监听消费者
        consumer1.close();
        session.close();
        connection.close();


    }
}